//
//  RZSportsVC.m
//  Sports-Go
//
//  Created by rimi on 16/9/22.
//  Copyright © 2016年 YRL. All rights reserved.
//

#import "RZSportsVC.h"
#import "TimeLabel.h"
#import "HWPopTool.h"
#import "IntroTextView.h"
@interface RZSportsVC ()
@property(nonatomic,strong)TimeLabel *timeLable;
@property(nonatomic,assign)BOOL isBegin;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)UIImageView *Sportsimageview;
@property(nonatomic,strong)NSMutableArray *ListArry1;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,strong)UILabel *bodyLabel;
@property(nonatomic,assign)NSInteger groupWithSportts;
@property(nonatomic,strong)UILabel *detailLable;
@property(nonatomic,strong)UILabel *nextLabel;
@property(nonatomic,strong)UIView *contentView;
@property(nonatomic,strong)NSString *introlString;
@property(nonatomic,assign)NSInteger timeCount;
@property(nonatomic,assign)CGFloat timeSports;
@end

@implementation RZSportsVC
-(void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playNetAnimation) name:@"playNext" object:nil];
    self.view.backgroundColor = [UIColor whiteColor];
    
    _timeLable = [[TimeLabel alloc]initWithFrame:CGRectMake(100, 0, 100, 100)];
    _timeLable.center = CGPointMake(self.view.center.x, 140*bi);
    _timeLable.textColor = getColor(58, 206, 248, 1);
    _timeLable.font = [UIFont boldSystemFontOfSize:40];
    _timeLable.minute = 1;
    _timeLable.second = 30;
    [self.view addSubview:_timeLable];
    [_timeLable controlTimeWith:NO];
    UIButton *button = [[UIButton alloc]init];
    button.frame = CGRectMake(80*bi, 550*bi, 80*bi, 30);//设置尺寸
    button.layer.cornerRadius = 10;
    button.layer.masksToBounds = YES;
    button.backgroundColor = getColor(58, 206, 248, 1);//背景色
    button.tag = 32;
    [button setTitle:@"暂停" forState: UIControlStateNormal];//普通
    [button setTitleColor:[UIColor whiteColor] forState:0];
    [button addTarget:self action:@selector(nextPage:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    _index = 0;
    _groupWithSportts = 0;
    _isBegin = YES;
    UIButton *exitButton = [[UIButton alloc]initWithFrame:CGRectMake(25, 40*bi, 40, 40)];
    [exitButton setImage:[UIImage imageNamed:@"叉"] forState:0];
    [exitButton addTarget:self action:@selector(action_exit) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exitButton];
    _Sportsimageview = [[UIImageView alloc]init];
    _Sportsimageview.bounds = CGRectMake(0, 0, 250*bi, 260*bi);
    _Sportsimageview.center = CGPointMake(self.view.center.x, self.view.center.y-30);
    _Sportsimageview.contentMode = UIViewContentModeScaleAspectFit;
   
   
    [self.view addSubview:_Sportsimageview];
    
    UIButton *nextButton = [[UIButton alloc]initWithFrame:CGRectMake(screen_size.width-160*bi, 550*bi, 80*bi, 30)];
    nextButton.layer.cornerRadius = 10;
    nextButton.layer.masksToBounds = YES;
    nextButton.backgroundColor = getColor(58, 206, 248, 1);
    [nextButton setTitle:@"下一组" forState:0];
    [nextButton setTitleColor:[UIColor whiteColor] forState:0];
    [nextButton addTarget:self action:@selector(nextSports:) forControlEvents:UIControlEventTouchUpInside];
    nextButton.tag = 31;
    [self.view addSubview:nextButton];
    
    UIButton *planButton = [[UIButton alloc]initWithFrame:CGRectMake(screen_size.width-130*bi, 445*bi, 20, 20)];
    [planButton setImage:[UIImage imageNamed:@"详情"] forState:0];
   
    [planButton addTarget:self action:@selector(plan_location) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:planButton];
    
    _contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 250*bi , 300*bi)];
    _contentView.backgroundColor = [UIColor clearColor];
    
    _ListArry1 = [NSMutableArray array];
    _ListArry1 = [self.dataSource[0][1] mutableCopy];
    [self.view addSubview:self.bodyLabel];
    [self playSportsWithGif:YES];
    self.bodyLabel.text = self.dataSource[0][0];
    [self.view addSubview:self.detailLable];
    self.detailLable.text = self.dataSource[0][1][0][@"sport_name"];
    [self.view addSubview:self.nextLabel];

   self.nextLabel.text = [NSString stringWithFormat:@"下一组:%@",self.dataSource[0][1][1][@"sport_name"]];
    _introlString = self.dataSource[0][1][0][@"sport_intro"];
}
//做运动
- (void)playSportsWithGif:(BOOL)flag{
     NSDictionary *dic = _ListArry1[_index];
    
    if (flag) {
        NSURL *url = [[NSBundle mainBundle]URLForResource:dic[@"sport_image"] withExtension:@".gif"];
        [_Sportsimageview sd_setImageWithURL:url];
    }else{
        _Sportsimageview.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.gif",dic[@"sport_image"]]];
    }
}
//下一组
- (void)nextSports:(UIButton *)sender{
    UIButton *button = [self.view viewWithTag:32];
    button.userInteractionEnabled = YES;
    button.backgroundColor = getColor(58, 206, 248, 1);
    _index ++;
   
    if (_index >= self.ListArry1.count) {
        _index = 0;
        [self playSportsWithGif:NO];
        [_timeLable suspendedTimeWith:YES];
        if (_groupWithSportts > 3) {
        [self alertViewEnd];
        }else{
        [self alertView];
        }
        
    }else{
        [self playSportsWithGif:YES];
        [_timeLable clearTime];
        _timeLable.second = 30;
        _timeLable.minute = 1;
        [_timeLable controlTimeWith:NO];
        self.detailLable.text = self.dataSource[_groupWithSportts][1][_index][@"sport_name"];
        if (_index == self.ListArry1.count-1) {
            
            if (_groupWithSportts > 3) {
            self.nextLabel.text = @"今日锻炼完成";
            }else{
            
            self.nextLabel.text = @"本组锻炼完成,即将进入下一节";
            }
            
        }else{
            
      self.nextLabel.text = [NSString stringWithFormat:@"下一组:%@",_ListArry1[_index+1][@"sport_name"]];
        }
        _introlString = _ListArry1[_index][@"sport_intro"];
        
    }
}
//训练部位
- (void)plan_location{
    IntroTextView *view = [[IntroTextView alloc]initWithFrame:_contentView.bounds];
    view.text = _introlString;
    view.layer.cornerRadius = 10;
    view.layer.masksToBounds = YES;
    [_contentView addSubview:view];
    [HWPopTool sharedInstance].shadeBackgroundType = ShadeBackgroundTypeSolid;
    [HWPopTool sharedInstance].closeButtonType = ButtonPositionTypeRight;
    [[HWPopTool sharedInstance] showWithPresentView:_contentView animated:YES];
}
//退出
- (void)action_exit{
    
    [_timeLable clearTime];
    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    if (userName && [[NSUserDefaults standardUserDefaults]objectForKey:@"isEnd"]) {

        [self saveSoprtsTimeAlert];
        
    }else{
    [self.navigationController popViewControllerAnimated:YES];
    
    }
}

- (void)saveSoprtsTimeAlert{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"训练完成,快来上传你的训练时间吧"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sportsTime:1];
    }];
    
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sportsTime:2];
    }];
    [alert addAction:ok];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];

}
- (void)sportsTime:(NSInteger)number{
    if (number == 1) {
        CGFloat sportsTime = 0.025 * _timeCount * 1.5;
      //网络请求 --- 保存运动时间
        NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
        AVQuery *query = [AVQuery queryWithClassName:@"t1"];
        
        [query whereKey:@"userID" equalTo:userName];
        
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (!error) {
                if (objects) {
            _timeSports = sportsTime + [objects.lastObject[@"time"] floatValue];
                    [self saveSportsTimeWith:userName];
                }else{
                    _timeSports = sportsTime;
                    [self saveSportsTimeWith:userName];
                }
                
            }else{
                [self warnWitherrorInfo:@"网络错误!"];
            }
            
        }];
 
    }else{
    [self.navigationController popViewControllerAnimated:YES];
    }
}
- (void)saveSportsTimeWith:(NSString *)userName{
      // NSLog(@"运动时间:%lf",_timeSports);
    AVObject *friendObject = [AVObject objectWithClassName:@"t1"];
    NSString *time = [NSString stringWithFormat:@"%0.4lf",_timeSports];
    //运动时间
    [friendObject setObject:userName forKey:@"userID"];
    [friendObject setObject:time forKey:@"time"];
    [friendObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            [self uploadSucessedWithInfo:@"上传成功,是否退出"];
        }else{
            [self uploadSucessedWithInfo:@"上传失败,是否退出"];
        }
    }];

}
//保存成功约否
- (void)uploadSucessedWithInfo:(NSString *)info{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"温馨提示" message:info preferredStyle:UIAlertControllerStyleAlert];
    //
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      [self.navigationController popViewControllerAnimated:YES];
    }];
    
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"取消" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
      
    }];
    [alert addAction:ok];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];

}


//暂停
- (void)nextPage:(UIButton *)sender{
    _isBegin = !_isBegin;
    UIButton *button = [self.view viewWithTag:31];
    if (_isBegin == NO) {
        [self playSportsWithGif:NO];
        [_timeLable suspendedTimeWith:YES];
        [sender setTitle:@"开始" forState:0];
     [UIView animateWithDuration:0.5 animations:^{
          button.hidden = YES;
     } completion:^(BOOL finished) {
    sender.frame = CGRectMake(screen_size.width/2-40, 550*bi, 80*bi, 30);
     }];
        
        
    }else{
        [sender setTitle:@"暂停" forState:0];
        [self playSportsWithGif:YES];
        [_timeLable suspendedTimeWith:NO];
        
        [UIView animateWithDuration:0.5 animations:^{
        sender.frame = CGRectMake(80*bi, 550*bi, 80*bi, 30);
            button.alpha = 0;
        } completion:^(BOOL finished) {
            button.alpha = 1;
            button.hidden = NO;
        }];
    }
}
//倒数时间结束
- (void)playNetAnimation{

    [self playSportsWithGif:NO];
    UIButton *button = [self.view viewWithTag:32];
    button.userInteractionEnabled = NO;
    button.backgroundColor = [UIColor lightGrayColor];
    NSString *userName = [[NSUserDefaults standardUserDefaults]objectForKey:@"userName"];
    
    if (userName) {
        _timeCount++;
        [[NSUserDefaults standardUserDefaults]setBool:YES forKey:@"isEnd"];
    }
}

- (UILabel *)bodyLabel{
    if (!_bodyLabel) {
        _bodyLabel = ({
      UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 40*bi,screen_size.width, 40)];
            label.textColor = getColor(58, 206, 248, 1);
            label.font = [UIFont boldSystemFontOfSize:20];
            label.textAlignment = NSTextAlignmentCenter;
        
            label;
        });
    }

    return _bodyLabel;
}
- (UILabel *)detailLable{
    if (!_detailLable) {
        _detailLable = ({
        
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 440*bi,screen_size.width, 30)];
            label.textColor = getColor(58, 206, 248, 1);
            label.font = [UIFont systemFontOfSize:15];
            label.textAlignment = NSTextAlignmentCenter;
            
            label;
       
        });
    }

    return _detailLable;
}
- (UILabel *)nextLabel{
    if (!_nextLabel) {
        _nextLabel = ({
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 490*bi,screen_size.width, 30)];
            label.textColor = getColor(58, 206, 248, 1);
            label.font = [UIFont boldSystemFontOfSize:15];
            label.textAlignment = NSTextAlignmentCenter;
            
            label;
        
        });
    }
    return _nextLabel;
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"sport_go" ofType:@"plist"]];
    }
    return _dataSource;
}
#pragma mark -- alter
- (void)alertView{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"你已训练完本节运动,请选择"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"下一节" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self playNextSports];
    }];
    
    UIAlertAction *cancle=[UIAlertAction actionWithTitle:@"再来一次" style: UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self playOnceAgain];
    }];
    
    [alert addAction:ok];
    [alert addAction:cancle];
    [self presentViewController:alert animated:YES completion:nil];
    
}
- (void)alertViewEnd{
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"你已完成今日训练,要劳逸结合,退出休息一下吧"] preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self action_exit];
    }];
    
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
    
}


//下一节
- (void)playNextSports{
    _groupWithSportts ++;
    [_ListArry1 removeAllObjects];
    if (_groupWithSportts < self.dataSource.count) {
        _ListArry1 = [self.dataSource[_groupWithSportts][1] mutableCopy];
        
        self.bodyLabel.text = self.dataSource[_groupWithSportts][0];
        
        [self playSportsWithGif:YES];
        [_timeLable clearTime];
        _timeLable.second = 30;
        _timeLable.minute = 1;
        [_timeLable controlTimeWith:NO];
    self.nextLabel.text = [NSString stringWithFormat:@"下一组:%@",self.dataSource[_groupWithSportts][1][1][@"sport_name"]];    
    }else{
        _groupWithSportts = 0;
    }
  
}



//再来一次
- (void)playOnceAgain{
    [self playSportsWithGif:YES];
    [_timeLable clearTime];
    _timeLable.second = 30;
    _timeLable.minute = 1;
    [_timeLable controlTimeWith:NO];
   self.detailLable.text = self.dataSource[_groupWithSportts][1][0][@"sport_name"];
    self.nextLabel.text = [NSString stringWithFormat:@"下一组:%@",self.dataSource[_groupWithSportts][1][1][@"sport_name"]];
}
- (void)warnWitherrorInfo:(NSString *)error{
    //警示框
    UILabel *label = [[UILabel alloc]initWithFrame:RzCGRectMake(90, 250, 185, 50)];
    label.backgroundColor = getColor(193, 162, 151, 1);
    label.textColor = [UIColor whiteColor];
    label.font = [UIFont systemFontOfSize:16];
    label.numberOfLines = 0;
    label.text = error;
    label.layer.cornerRadius = 5;
    label.layer.masksToBounds = YES;
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];
    [UIView animateWithDuration:2.0 animations:^{
        label.alpha = 0.0;
    } completion:^(BOOL finished) {
        
        [label removeFromSuperview];
    }];
    
    
}


- (void)viewWillDisappear:(BOOL)animated{
   self.tabBarController.tabBar.hidden = NO;
    [[NSUserDefaults standardUserDefaults]removeObjectForKey:@"isEnd"];
}
@end
